package org.ftc.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class TxtUtil {

	public static class Txt {
		
		public long serial(String name){
			File file = new File(new File(Global.APP.HOME_PATH), name);
			Long count = TxtUtil.readTxt(file);
			TxtUtil.writeTxt( count, file ); 
			return count;
		}
	}
	
	private synchronized static Long readTxt(File file){
		Long contents = null;
		try{
			String text = null;
			BufferedReader reader = new BufferedReader(new FileReader(file));
			while ((text = reader.readLine()) != null)
				contents = new Long(text);
			reader.close();  
		}catch( Exception e){
			e.printStackTrace();
		}
		return ( contents + 1 ); 
	}  
	
	private synchronized static void writeTxt(Long count, File file){
		try{
			BufferedWriter out = new BufferedWriter( new FileWriter( file ) );
			out.write( count.toString() );
			out.flush();   
			out.close();
		}catch( Exception e){
			e.printStackTrace();
		}
	}  
	
	public synchronized static File writeCsv(List<HashMap<String, Object>> list){
		try{
			File tmp = File.createTempFile("txt", UUID.randomUUID()+".txt");
			BufferedWriter out = new BufferedWriter( new FileWriter( tmp ) );
			
			if( list != null && list.size() > 0 ){
				//title
				HashMap<String, Object> title =  list.get(0);
				for(Iterator<String> it = title.keySet().iterator(); it.hasNext(); ){
					out.write( it.next() + "\t");
				}
				out.write( "\n" );
				//內容
				for(HashMap<String, Object> map : list ){
					if( map != null && map.size() > 0 ){
						for(Iterator<String> it = map.keySet().iterator(); it.hasNext(); ){
							Object o = map.get(it.next());
							out.write( o == null ? "null" : o.toString() );
							out.write( "\t");
						}	
					}
					out.write( "\n" );
				}
			}
			out.flush();   
			out.close(); 
			return tmp;
		}catch( Exception e){
			e.printStackTrace();
			return null;
		}
	} 
}
